package com.itheima.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.IdUtil;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.RegisteredPayload;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.ThreadLocalUtil;
import com.itheima.dto.AttentionDto;
import com.itheima.dto.LoginDto;
import com.itheima.po.Attention;
import com.itheima.po.User;
import com.itheima.vo.UserVo;
import com.itheima.mapper.AttentionMapper;
import com.itheima.mapper.UserMapper;
import com.itheima.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author :wujunjie
 * createTime :2022-12-27 15:11
 * description :
 */

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AttentionMapper attentionMapper;

    @Override
    public UserVo login(LoginDto loginDto) {
        if (ObjectUtils.isEmpty(loginDto)){
            throw new RuntimeException("入参不得为空");
        }
        if (StringUtils.isEmpty(loginDto.getPhone())&&StringUtils.isEmpty(loginDto.getPassword())){
            String token = getToken(0L);
            UserVo userVo = new UserVo();
            userVo.setUser(null);
            userVo.setToken(token);
            return userVo;
        }

        boolean mobile = Validator.isMobile(loginDto.getPhone());
        if (!mobile){
            throw new RuntimeException("手机号格式不正确");
        }
        LambdaQueryWrapper<User> lqw=new LambdaQueryWrapper<>();
        lqw.eq(User::getPhone,loginDto.getPhone());
        User userInDB=userMapper.selectOne(lqw);
        User user = new User();
        if (ObjectUtils.isEmpty(userInDB)){
            //数据库中没有电话记录就走注册
            user.setId(IdUtil.getSnowflakeNextId());
            user.setPhone(loginDto.getPhone());
            user.setName("");
            user.setImage("");
            user.setSex(true);
            user.setStatus(true);
            user.setIsIdentityAuthentication(false);
            user.setFlag(0);
            user.setCreateTime(LocalDateTime.now());
            int insert = userMapper.insert(user);
            if (insert!=1){
                throw new RuntimeException("添加失败");
            }
        }else {
            BeanUtils.copyProperties(userInDB,user);
        }

        //数据库中有记录就走登录
        String token = getToken(user.getId());
        UserVo userVo = new UserVo();
        userVo.setUser(user);
        userVo.setToken(token);
        return userVo;
    }

    @Override
    public Boolean attention(AttentionDto attentionDto) {
        if (ObjectUtils.isEmpty(attentionDto)){
            throw new RuntimeException("入参不得为空");
        }
        if (ObjectUtils.isEmpty(attentionDto.getOperation())||StringUtils.isEmpty(attentionDto.getAuthorId())||StringUtils.isEmpty(attentionDto.getArticleId())){
            throw new RuntimeException("入参字段不得为空");
        }
        Attention attention = new Attention();
        BeanUtils.copyProperties(attentionDto,attention);
        attention.setUserId(Long.parseLong(ThreadLocalUtil.getId()));
        LambdaQueryWrapper<Attention> lqw=new LambdaQueryWrapper<>();
        lqw.eq(Attention::getArticleId,attention.getArticleId());
        lqw.eq(Attention::getAuthorId,attention.getAuthorId());
        lqw.eq(Attention::getUserId,attention.getUserId());
        Attention attentionInDb = attentionMapper.selectOne(lqw);
        if (ObjectUtils.isEmpty(attentionInDb)){
            attention.setId(IdUtil.getSnowflakeNextId());
            attention.setCreateTime(LocalDateTime.now());
            int insert = attentionMapper.insert(attention);
            return insert==1;
        }

        BeanUtils.copyProperties(attentionInDb,attention);
        attention.setOperation(attentionDto.getOperation());
        int updateById = attentionMapper.updateById(attention);
        return updateById==1;
    }

    private static String getToken(Long id) {
        DateTime now = DateUtil.date();
        DateTime exp = DateUtil.offset(now, DateField.HOUR, 24);
        Map<String,Object> payload=new HashMap<>();
        payload.put(RegisteredPayload.ISSUED_AT,now);
        payload.put(RegisteredPayload.NOT_BEFORE, now);
        payload.put(RegisteredPayload.EXPIRES_AT,exp);
        payload.put("id",id);
        return JWTUtil.createToken(payload, "heimaLeadnews".getBytes());
    }
}
